package com.chen.blue.service.system.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.blue.annotation.permission.DataPermission;
import com.chen.blue.container.PermissionFlag;
import com.chen.blue.converter.system.DeptConverter;
import com.chen.blue.converter.system.MenuConverter;
import com.chen.blue.dictionary.CommonDict;
import com.chen.blue.dictionary.UserConstants;
import com.chen.blue.domain.delete.system.MenuDelete;
import com.chen.blue.domain.dto.system.MenuAllDto;
import com.chen.blue.domain.dto.system.MenuButtonDto;
import com.chen.blue.domain.dto.system.MenuDirectoryDto;
import com.chen.blue.domain.dto.system.MenuDto;
import com.chen.blue.domain.dto.system.update.*;
import com.chen.blue.domain.model.system.DeptModel;
import com.chen.blue.domain.model.system.MenuModel;
import com.chen.blue.domain.model.system.PostModel;
import com.chen.blue.domain.query.system.MenuQuery;
import com.chen.blue.domain.vo.router.MetaVo;
import com.chen.blue.domain.vo.router.RouterVo;
import com.chen.blue.domain.vo.system.DeptVo;
import com.chen.blue.domain.vo.system.MenuVo;
import com.chen.blue.exception.e.DtoNullException;
import com.chen.blue.mapper.system.MenuMapper;
import com.chen.blue.result.DataResult;
import com.chen.blue.service.candidate.CandidateInfoService;
import com.chen.blue.service.system.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.blue.utils.PageInfoUtil;
import com.chen.blue.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author CLT
 * @since 2024-04-29
 */
@Service("iMenuService")
public class IMenuServiceImpl extends ServiceImpl<MenuMapper, MenuModel> implements IMenuService {


    @Override
    public boolean addMenu(MenuAllDto menuAllDto) throws DtoNullException {

        if (Objects.isNull(menuAllDto)) {
            throw new DtoNullException("参数为空");
        }

        MenuDto menuDto = menuAllDto.getMenuDto();
        MenuButtonDto menuButtonDto = menuAllDto.getMenuButtonDto();
        MenuDirectoryDto menuDirectoryDto = menuAllDto.getMenuDirectoryDto();

        valid(menuDto, menuButtonDto, menuDirectoryDto, false);

        return Objects.nonNull(menuDto) ? super.save(MenuConverter.dtoToModel(menuDto)) : Objects.nonNull(menuButtonDto) ? super.save(MenuConverter.dtoToModel(menuButtonDto)) : super.save(MenuConverter.dtoToModel(menuDirectoryDto));

    }

    @Override
    public boolean deleteMenu(MenuDelete menuDelete) throws DtoNullException {

        if (Objects.isNull(menuDelete)) {
            throw new DtoNullException("参数为空");
        }

        Map<String, Object> wrap = new HashMap<>();
        if (Objects.nonNull(menuDelete.getId())) {
            wrap.put("id", menuDelete.getId());
        }

        return Objects.nonNull(menuDelete.getIds()) ? super.removeByIds(menuDelete.getIds()) : super.removeByMap(wrap);

    }

    @Override
    public boolean updateMenuById(MenuAllDtoEdit menuAllDtoEdit) throws DtoNullException {

        if (Objects.isNull(menuAllDtoEdit)) {
            throw new DtoNullException("参数为空");
        }

        MenuDtoEdit menuDtoEdit = menuAllDtoEdit.getMenuDtoEdit();
        MenuButtonDtoEdit menuButtonDtoEdit = menuAllDtoEdit.getMenuButtonDtoEdit();
        MenuDirectoryDtoEdit menuDirectoryDtoEdit = menuAllDtoEdit.getMenuDirectoryDtoEdit();

        valid(menuDtoEdit, menuButtonDtoEdit, menuDirectoryDtoEdit, true);

        return Objects.nonNull(menuDtoEdit) ? super.updateById(MenuConverter.dtoEditToModel(menuDtoEdit)) : Objects.nonNull(menuButtonDtoEdit) ? super.updateById(MenuConverter.dtoEditToModel(menuButtonDtoEdit)) : super.updateById(MenuConverter.dtoEditToModel(menuDirectoryDtoEdit));

    }

    @DataPermission
    @Override
    public DataResult<List<MenuVo>> queryMenu(MenuQuery menuQuery, boolean isTree) throws DtoNullException {

        if (Objects.isNull(menuQuery)) {
            throw new DtoNullException("查询条件为空");
        }

        LambdaQueryWrapper<MenuModel> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(menuQuery.getPageNo()) && Objects.nonNull(menuQuery.getPageSize())) {
            PageHelper.startPage(menuQuery.getPageNo(), menuQuery.getPageSize());
        }
        if (Objects.nonNull(menuQuery.getName())) {
            wrapper.like(MenuModel::getName, menuQuery.getName());
        }
        if (Objects.nonNull(menuQuery.getStatus())) {
            wrapper.eq(MenuModel::getStatus, menuQuery.getStatus());
        }

        List<MenuModel> menuModelList = super.list(wrapper);
        PageInfo<MenuModel> pageInfo = new PageInfo<>(menuModelList);
        PageHelper.clearPage();

        // 关闭数据权限
        PermissionFlag.set(false);

        /**
         * 统一结果返回
         */
        DataResult<List<MenuVo>> dataResult = new DataResult<>();
        List<MenuVo> menuVoList = MenuConverter.modelToVoList(pageInfo.getList());
        // 返回树形结构
        List<MenuVo> list = MenuConverter.modelToVoList(pageInfo.getList());
        List<MenuVo> menuVoTree = Objects.isNull(list) ? null : list.size() == 1 ? queryMenuById(list.get(0).getId()).getResult() : getMenuVoTree(0L, null, list);
        // 判断是否返回树形结构
        dataResult.setData(isTree ? menuVoTree : menuVoList);
        PageInfoUtil.setPageInfo(dataResult, pageInfo);

        return dataResult;

    }

    @Override
    public DataResult<List<MenuVo>> queryMenuById(Long id) throws DtoNullException {

        if (Objects.isNull(id)) {
            throw new DtoNullException("ID为空");
        }

        MenuModel menuModel = super.getById(id);
        DataResult<List<MenuVo>> dataResult = new DataResult<>();
        MenuVo menuVo = MenuConverter.modelToVo(menuModel);
        List<MenuVo> menuVoList = getMenuVoTreeById(menuVo != null ? menuVo.getId() : null, MenuConverter.modelToVoList(super.list()));
        dataResult.setData(menuVoList);

        return dataResult;

    }

    @DataPermission
    @Override
    public DataResult<List<RouterVo>> queryRouter() throws DtoNullException {

        MenuQuery menuQuery = new MenuQuery().setStatus(null).setName(null);
        menuQuery.setPageNo(null);
        menuQuery.setPageSize(null);

        DataResult<List<MenuVo>> menuVoDataResult = queryMenu(menuQuery, true);
        List<RouterVo> routerVos = buildMenus(menuVoDataResult.getResult());

        DataResult<List<RouterVo>> dataResult = new DataResult<>();
        dataResult.setData(routerVos);

        return dataResult;
    }

    protected void valid(MenuDto menuDto, MenuButtonDto menuButtonDto, MenuDirectoryDto menuDirectoryDto, boolean isUpdate) throws DtoNullException {

        boolean b1 = Objects.isNull(menuDirectoryDto);
        boolean b2 = Objects.isNull(menuDto);
        boolean b3 = Objects.isNull(menuButtonDto);

        if (!b1 && !isUpdate) {
            CandidateInfoService.setCreator(menuDirectoryDto);
        } else if (!b2 && !isUpdate) {
            CandidateInfoService.setCreator(menuDto);
        } else if (!b3 && !isUpdate) {
            CandidateInfoService.setCreator(menuButtonDto);
        } else {
            CandidateInfoService.setUpdater(!b1 ? menuDirectoryDto : !b2 ? menuDto : menuButtonDto);
        }

        if (b1 && b2 && b3) {
            throw new DtoNullException("参数为空");
        }

        if ((!b1 && !b2) || (!b1 && !b3) || (!b2 && !b3) || (!b1 && !b2 && !b3)) {
            throw new DtoNullException("参数错误");
        }

    }


    /**
     * 返回整体菜单的树形结构
     *
     * @param menuVoList
     * @return
     */
    protected List<MenuVo> getMenuVoTree(Long parentId, String parentName, List<MenuVo> menuVoList) {

        if (Objects.isNull(menuVoList) || Objects.isNull(parentId)) {
            return null;
        }

        return menuVoList.stream()
                .filter(obj -> obj.getParentId().equals(parentId))
                .map(obj -> {
                    obj.setChildren(setChildrenList(obj.getId(), obj.getName(), menuVoList));
                    obj.setParentName(parentName);
                    return obj;
                })
                .collect(Collectors.toList());
    }

    /**
     * 返回指定id的菜单及其子菜单
     *
     * @param id
     * @param menuVoList
     * @return
     */
    protected List<MenuVo> getMenuVoTreeById(Long id, List<MenuVo> menuVoList) {

        if (Objects.isNull(menuVoList) || Objects.isNull(id)) {
            return null;
        }

        return menuVoList.stream()
                .filter(obj -> obj.getId().equals(id))
                .peek(obj -> obj.setChildren(setChildrenList(obj.getId(), obj.getName(), menuVoList)))
                .collect(Collectors.toList());
    }


    /**
     * 返回指定id的子菜单
     *
     * @param parentId
     * @param list
     * @return
     */
    protected List<MenuVo> setChildrenList(Long parentId, String parentName, List<MenuVo> list) {

        return list.stream().filter(obj -> obj.getParentId().equals(parentId))
                .map(obj -> {
                    obj.setChildren(setChildrenList(obj.getId(), obj.getName(), list));
                    obj.setParentName(parentName);
                    return obj;
                }).collect(Collectors.toList());

    }


    /**
     * 根据菜单获取路由
     *
     * @param menus
     * @return
     */
    protected List<RouterVo> buildMenus(List<MenuVo> menus) {
        if (Objects.isNull(menus)) {
            return null;
        }
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (MenuVo menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getKeepAlive(), null));
            List<MenuVo> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && CommonDict.DIRECTORY_TYPE.equals(menu.getType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getKeepAlive(), null));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }


    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(MenuVo menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(MenuVo menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && CommonDict.DIRECTORY_TYPE.equals(menu.getType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(MenuVo menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(MenuVo menu) {
        return menu.getParentId().intValue() == 0 && CommonDict.MENU_TYPE.equals(menu.getType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(MenuVo menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(MenuVo menu) {
        return menu.getParentId().intValue() != 0 && CommonDict.DIRECTORY_TYPE.equals(menu.getType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<MenuVo> getChildPerms(List<MenuVo> list, int parentId) {
        List<MenuVo> returnList = new ArrayList<MenuVo>();
        for (Iterator<MenuVo> iterator = list.iterator(); iterator.hasNext(); ) {
            MenuVo t = (MenuVo) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<MenuVo> list, MenuVo t) {
        // 得到子节点列表
        List<MenuVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MenuVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<MenuVo> getChildList(List<MenuVo> list, MenuVo t) {
        List<MenuVo> tlist = new ArrayList<MenuVo>();
        Iterator<MenuVo> it = list.iterator();
        while (it.hasNext()) {
            MenuVo n = (MenuVo) it.next();
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MenuVo> list, MenuVo t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{CommonDict.HTTP, CommonDict.HTTPS, CommonDict.WWW, ".", ":"},
                new String[]{"", "", "", "/", "/"});
    }


}
